//
//  FollowReadingViewController.m
//  KidReading
//
//  Created by YangShuai on 16/9/27.
//  Copyright © 2016年 刘赞黄Telen. All rights reserved.
//

#import "FollowReadingViewController.h"
#import "ConstDefine.h"

typedef enum : NSUInteger{
    ShowType_Normal = 1,
    ShowType_Medium,
    ShowType_Large,
}ShowType;

@interface FollowReadingViewController ()<UITableViewDelegate,UITableViewDataSource>{
    CGFloat topBarHeight;
}
@property(nonatomic,strong)NSArray* textSenArray;
@property(nonatomic,strong)NSArray* ASRSenArray;
@property(nonatomic,strong)NSArray* textRangeArray;
@property(nonatomic,strong)UITableView* tableView;
@property(nonatomic,strong)FollowReadingTableViewCell* currentCell;
//
@property(nonatomic,strong)NSArray* serverReusltsArray;
@property(nonatomic,strong)NSArray* finalResultsArray;
@end

@implementation FollowReadingViewController{
    BOOL _isHorizontalScreen;
    ShowType _showType;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //
    if ([[UIApplication sharedApplication] statusBarOrientation] == UIInterfaceOrientationPortrait || [[UIApplication sharedApplication] statusBarOrientation] == UIInterfaceOrientationPortraitUpsideDown) {
        _isHorizontalScreen = NO;
    }else{
        _isHorizontalScreen = YES;
    }
    //
    [[UIApplication sharedApplication] setStatusBarHidden:YES];
    //
    [self forceOrientationTo:self.rotation_to];
    //
    [self changeSingleTextArrayToTextArray];
    [self creatASRTextArray];
    //
    if (_textSenArray.count == 1) {
        _showType = ShowType_Large;
    }else if (_textSenArray.count == 2 || _textSenArray.count == 3){
        _showType = ShowType_Medium;
    }else{
        _showType = ShowType_Normal;
    }
    //
    [self creatTableView];
    //创建title
    self.view.backgroundColor = [UIColor colorWithHexString:@"#F0F1F5"];
    [self addTopBarView];
    ////
    [self getLocalASRResultsInPage];
    [self getSeverASRResultsInPage];
}

- (void)addTopBarView
{
    UIImage* image = [UIImage imageNamed:@"public_topbar.png"];
    topBarHeight = image.size.height;
    CGFloat topEmpty = 8/ratio_w;
    CGFloat w = width_my;
    CGRect frame = CGRectMake(0, 0, w, topBarHeight);
    //frame.origin.y = -topBarHeight;
    UIView* topBarView = [[UIView alloc] initWithFrame:frame];
    topBarView.backgroundColor = [UIColor colorWithPatternImage:image];
    [self.view addSubview:topBarView];
    //
    //title
    CGFloat x = 90/ratio_w;
    frame = CGRectMake(x*2, 0, w-x*4, topBarHeight-topEmpty);
    UILabel* titleLabel = [[UILabel alloc] initWithFrame:frame];
    titleLabel.text = NSLocalizedString(@"readAfterMe", "");
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.font = [UIFont boldSystemFontOfSize:frame.size.height*0.35];
    titleLabel.textColor = [UIColor whiteColor];
    [topBarView addSubview:titleLabel];
    
    //arrow
    w = 140/ratio_w;
    CGFloat h = topBarHeight-topEmpty;
    UIView* view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, w, h)];
    view.backgroundColor = [UIColor clearColor];
    [topBarView addSubview:view];
    //
    TLTapImageView* imgv = [[TLTapImageView alloc] initWithFrame:CGRectMake(0, 0, 44/ratio_w, 44/ratio_w)];
    imgv.normalImage = [UIImage imageNamed:@"public_icon_leftarrow.png"];
    imgv.selectImage = [UIImage imageNamed:@"public_icon_leftarrow.png"];
    imgv.image = imgv.normalImage;
    imgv.center = CGPointMake(40/ratio_w, h/2);
    [view addSubview:imgv];
    //tap
    UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapBack)];
    tap.numberOfTapsRequired = 1;
    tap.numberOfTouchesRequired = 1;
    [view addGestureRecognizer:tap];
    tap.delegate = [TLGestureRecognizerDelegate shareSingleTapView];
}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarHidden:YES];
}

//获取本地数据库评测结果
-(void)getLocalASRResultsInPage{
    UserInfo* uinfo = [CacheData shareSingle].getUserLoginInfo;
    [[DBHelper shareInstance] followReading_getDictList:^(NSArray *list) {
        if (list.count > 0) {
            self.finalResultsArray = list;
            [_tableView reloadData];
        }
    } fromTableClass:NSStringFromClass([OneWordASRResult class]) where:[NSString stringWithFormat:@"where userId = %@ and bookId = %@ and pageIndex = %@ order by senIndex desc",@(uinfo.uid),@(_bookId),@(_pageId)]];
}
//获取本地评测结果列表(不reloadData)
-(void)getLocalASRResultsInPageNotReloadData{
    UserInfo* uinfo = [CacheData shareSingle].getUserLoginInfo;
    [[DBHelper shareInstance] followReading_getDictList:^(NSArray *list) {
        if (list.count > 0) {
            self.finalResultsArray = list;
        }
    } fromTableClass:NSStringFromClass([OneWordASRResult class]) where:[NSString stringWithFormat:@"where userId = %@ and bookId = %@ and pageIndex = %@ order by senIndex desc",@(uinfo.uid),@(_bookId),@(_pageId)]];
}

//获取服务器存储评测结果
-(void)getSeverASRResultsInPage{
    [[NetGetPostsWithCache shareInstance] updateOrGetOnePageRadioEvalsWithBookId:_bookId PageIndex:_pageId EvalJsonStr:nil Success:^(NSDictionary *retDict) {
        //本地数据与服务器数据对比同步
        NSArray* severListArray = retDict[@"data"];
        NSMutableArray* severListArray_DB = [NSMutableArray new];
        
        for (NSDictionary* severDict in severListArray) {
            for (NSDictionary* localDict in _finalResultsArray) {
                if ([localDict[@"senIndex"] integerValue] == [severDict[@"senIndex"] integerValue]) {
                    if ([severDict[@"radioSrc"] compare:localDict[@"radioSrc"]]) {
                        [[DB_NetFollowReading shareSingle] removeCurrentLocalRecordWithBookId:_bookId PageIndex:_pageId SenIndex:[localDict[@"senIndex"] integerValue]];
                    }
                }
            }
            NSMutableDictionary* newlocalDict = [NSMutableDictionary dictionaryWithDictionary:severDict];
            [newlocalDict removeObjectForKey:@"updateAt"];
            [severListArray_DB addObject:newlocalDict];
        }
        [[DBHelper shareInstance] followReading_updateListToTableClass:NSStringFromClass([OneWordASRResult class]) dictArr:severListArray_DB complete:^{
            //重新获取
            [self getLocalASRResultsInPage];
        }];
        
    } Failure:^(NSError *error) {
        
    }];
}

//把数组转化为可显示的字符串数组
-(void)changeSingleTextArrayToTextArray{
    NSMutableArray* sensArray = [NSMutableArray new];
    NSMutableArray* sensRangeArray = [NSMutableArray new];
    for (int i = 0; i < _showTextArray.count; i ++) {
        NSArray* oneSenArray = _showTextArray[i];
        NSString* oneSen = [oneSenArray componentsJoinedByString:@""];
        [sensArray addObject:oneSen];
        //RangeArray
        NSUInteger location = 0;
        NSMutableArray* rangeArray_one = [NSMutableArray new];
        for (NSString* oneText in oneSenArray) {
            NSRange textRange = NSMakeRange(location, oneText.length);
            location += oneText.length;
            [rangeArray_one addObject:[NSValue valueWithRange:textRange]];
        }
        [sensRangeArray addObject:rangeArray_one];
    }
    self.textSenArray = sensArray;
    self.textRangeArray = sensRangeArray;
}

//转化为可检测的字符串数组
-(void)creatASRTextArray{
    NSMutableArray* ASRTextArray = [NSMutableArray new];
    for (int i = 0; i < _ASRTextArray.count; i ++) {
        NSArray* oneTextArray = _ASRTextArray[i];
        NSString* oneText = [oneTextArray componentsJoinedByString:@","];
        if ([_textLangArray[i] integerValue] == 1) {
            oneText = [oneTextArray componentsJoinedByString:@""];
        }
        [ASRTextArray addObject:oneText];
    }
    self.ASRSenArray = ASRTextArray;
}

//多条数据
-(void)creatTableView{
    self.tableView = [[UITableView alloc] init];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.tableView];
    if (_showType == ShowType_Large) {
        CGFloat tableViewHeight = [self getTableViewHeight:[_textSenArray firstObject]];
        self.tableView.bounces = NO;
        if (_isHorizontalScreen) {
            [self.tableView JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
                make.left.JRMAS_equalTo(130);
                make.right.JRMAS_equalTo(-130);
                make.top.JRMAS_equalTo(53);
                make.bottom.JRMAS_equalTo(0);
            }];
            if ([DataProcessing shareSingle].deviceType == DevicesTypes_iPhone) {
                [self.tableView JRMAS_remakeConstraints:^(JRMASConstraintMaker *make) {
                    make.left.JRMAS_equalTo(130 / ratio_w);
                    make.right.JRMAS_equalTo(-130 / ratio_w);
                    make.top.JRMAS_equalTo(35);
                    make.bottom.JRMAS_equalTo(0);
                }];
            }
        }else{
            [self.tableView JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
                make.centerY.JRMAS_equalTo(0).offset(30);
                make.left.right.JRMAS_equalTo(0);
                make.height.JRMAS_equalTo(tableViewHeight);
            }];
            if ([DataProcessing shareSingle].deviceType == DevicesTypes_iPhone) {
                [self.tableView JRMAS_remakeConstraints:^(JRMASConstraintMaker *make) {
                    make.centerY.JRMAS_equalTo(0).offset(15);
                    make.left.right.JRMAS_equalTo(0);
                    make.height.JRMAS_equalTo(tableViewHeight);
                }];
            }
        }
    }else{
        [self.tableView JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
            make.edges.JRMAS_equalTo(UIEdgeInsetsMake(53, 0, 0, 0));
        }];
        if ([DataProcessing shareSingle].deviceType == DevicesTypes_iPhone) {
            [self.tableView JRMAS_remakeConstraints:^(JRMASConstraintMaker *make) {
                make.edges.JRMAS_equalTo(UIEdgeInsetsMake(35, 0, 0, 0));
            }];
        }
    }
    [self.tableView registerClass:[FollowReadingTableViewCell class] forCellReuseIdentifier:_id_FollowReadingTableViewCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"FollowReadingTableViewCell" bundle:nil] forCellReuseIdentifier:_id_FollowReadingTableViewCell];
    //
    [self.tableView registerClass:[MediumFollowReadingTableViewCell class] forCellReuseIdentifier:_id_MediumFollowReadingTableViewCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"MediumFollowReadingTableViewCell" bundle:nil] forCellReuseIdentifier:_id_MediumFollowReadingTableViewCell];
    //
    [self.tableView registerClass:[LargeFollowReadingTableViewCell class] forCellReuseIdentifier:_id_LargeFollowReadingTableViewCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"LargeFollowReadingTableViewCell" bundle:nil] forCellReuseIdentifier:_id_LargeFollowReadingTableViewCell];
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.showsHorizontalScrollIndicator = NO;
}

//一句话时计算tableView的高度
-(CGFloat)getTableViewHeight:(NSString*)text{
    CGFloat width = self.view.width - 120 / ratio_w;
    CGFloat font = 36 / ratio_w;
    if (_isHorizontalScreen) {
        width = self.view.width - 260 / ratio_w;
    }
    CGSize labelSize = [UILabel contentSizeForStr:text withFont:[UIFont systemFontOfSize:font] withBreakMode:NSLineBreakByCharWrapping withTestAlignment:NSTextAlignmentLeft withRestrainWidth:width andHeight:1000];
    return labelSize.height + 560 / ratio_w;
}


-(void)tapBack{
    [self dismissViewControllerAnimated:YES completion:nil];
    [self dealloc_My];
}


#pragma mark - UITableViewDelegate

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _textSenArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_showType == ShowType_Large) {
        NSString* text = _textSenArray[indexPath.row];
        CGFloat labelHeight = [self getTableViewHeight:text];
        if (_isHorizontalScreen) {
            if (labelHeight < self.view.height) {
                labelHeight = self.view.height - 53;
                if ([DataProcessing shareSingle].deviceType == DevicesTypes_iPhone) {
                    labelHeight = self.view.height - 35;
                }
            }
        }else{
            if (labelHeight > self.view.height) {
                labelHeight = self.view.height - 53;
                if ([DataProcessing shareSingle].deviceType == DevicesTypes_iPhone) {
                    labelHeight = self.view.height - 35;
                }
            }
        }
        return labelHeight;
    }else if (_showType == ShowType_Medium){
        NSString* text = _textSenArray[indexPath.row];
        CGFloat labelHeight = [self cellHeightWithText:text];
        return labelHeight + 300 / ratio_w;
    }else{
        NSString* text = _textSenArray[indexPath.row];
        CGFloat labelHeight = [self cellHeightWithText:text];
        return labelHeight + 150 / ratio_w;
    }
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell* cell = nil;
    NSString* text = _textSenArray[indexPath.row];
    FollowReadingTableViewCell *followReadingCell = nil;
    if (_showType == ShowType_Large) {
        followReadingCell = [tableView dequeueReusableCellWithIdentifier:_id_LargeFollowReadingTableViewCell];
    }else if (_showType == ShowType_Medium){
        followReadingCell = [tableView dequeueReusableCellWithIdentifier:_id_MediumFollowReadingTableViewCell];
    }else{
        followReadingCell = [tableView dequeueReusableCellWithIdentifier:_id_FollowReadingTableViewCell];
    }
    [followReadingCell cleanCellInfo];
    followReadingCell.showTextLabel.text = text;
    followReadingCell.mp3Path = [_mp3Array objectAtIndex:indexPath.row];
    followReadingCell.bookId = _bookId;
    followReadingCell.pageId = _pageId;
    followReadingCell.sentenceId = indexPath.row + 1;
    followReadingCell.ASRText = _ASRSenArray[indexPath.row];
    followReadingCell.rangeArray = _textRangeArray[indexPath.row];
    followReadingCell.ASRWordArray = _ASRTextArray[indexPath.row];
    followReadingCell.selectionStyle = UITableViewCellSelectionStyleNone;
    followReadingCell.isEnText = [_textLangArray[indexPath.row] integerValue];
    for (NSDictionary* localResultDict in self.finalResultsArray) {
        if ([localResultDict[@"senIndex"] integerValue] == indexPath.row + 1) {
            followReadingCell.localResultDict = localResultDict;
        }
    }
    [[DB_NetFollowReading shareSingle] checkCellIsRuningWithBookId:_bookId PageIndex:_pageId SentenceId:indexPath.row + 1 Complete:^(BOOL isRuning, StatusButton *runingButton, NSTimeInterval currentTime) {
        if (isRuning) {
            [runingButton startRunWithTotleTime:runingButton.totleTime CurrentTime:currentTime];
        }
    }];
    cell = followReadingCell;
    if (indexPath.row % 2 == 0) {
        cell.backgroundColor = [UIColor whiteColor];
    }else{
        cell.backgroundColor = [UIColor clearColor];
    }
    [followReadingCell checkRecordExist];
    
    followReadingCell.tapPlayOri = ^(FollowReadingTableViewCell* cell){
        if (_currentCell != cell) {
            [_currentCell stopAllRuningButton];
            self.currentCell = cell;
        }else{
            self.currentCell = cell;
        }
    };
    followReadingCell.tapRecord = ^(FollowReadingTableViewCell* cell){
        if (_currentCell != cell) {
            [_currentCell stopAllRuningButton];
            self.currentCell = cell;
        }else{
            self.currentCell = cell;
        }
    };
    followReadingCell.tapPlayRecord = ^(FollowReadingTableViewCell* cell){
        if (_currentCell != cell) {
            [_currentCell stopAllRuningButton];
            self.currentCell = cell;
        }else{
            self.currentCell = cell;
        }
    };
    followReadingCell.syncAllResultsArray = ^(){
        [self getLocalASRResultsInPageNotReloadData];
    };
    return cell;
}

//计算Cell高度
-(CGFloat)cellHeightWithText:(NSString*)text{
    CGFloat width = self.view.width - 40 / ratio_w - 200 / ratio_w;
    CGFloat font = 24 / ratio_w;
    if (_showType == ShowType_Medium) {
        width = self.view.width - 90 / ratio_w;
        font = 30 / ratio_w;
    }else if (_showType == ShowType_Large){
        width = self.view.width - 120 / ratio_w;
        font = 36 / ratio_w;
    }
    
    CGSize labelSize = [UILabel contentSizeForStr:text withFont:[UIFont systemFontOfSize:font] withBreakMode:NSLineBreakByCharWrapping withTestAlignment:NSTextAlignmentLeft withRestrainWidth:width andHeight:1000];
    return labelSize.height;
}

-(void)dealloc_My{
    [super dealloc_My];
    [[TLSoundPlayer shareSingle] stopAllFiles_andClean];
    [[JRASRManager defaultManager] stopRecord];
}

-(void)applicationDidEnterBackground:(UIApplication *)application{
    [_currentCell stopAllRuningButton];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
